package com.example.administrator.szb.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.example.administrator.szb.R;
import com.example.administrator.szb.activity.base.BasePresenter;
import com.example.administrator.szb.activity.base.MVPBaseFragmentActivity;
import com.example.administrator.szb.activity.luyan.LuYanNewActivity;
import com.example.administrator.szb.activity.supei.SuPeiNew2Activity;
import com.example.administrator.szb.activity.supei.SuPeiNewActivity;
import com.example.administrator.szb.bean.DownIngBean;
import com.example.administrator.szb.bean.JpushBean;
import com.example.administrator.szb.bean.SuPeiBuiness;
import com.example.administrator.szb.bean.UserBase;
import com.example.administrator.szb.fragments.fragment_forTab.FragmentAsk;
import com.example.administrator.szb.fragments.fragment_forTab.FragmentMy2;
import com.example.administrator.szb.fragments.fragment_forTab.FragmentMy3;
import com.example.administrator.szb.fragments.fragment_forTab.FragmentTools;
import com.example.administrator.szb.fragments.fragment_forTab.home.FragmentHome;
import com.example.administrator.szb.http.HttpUtils;
import com.example.administrator.szb.http.OnResultListener;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.AndroidSetView;
import com.example.administrator.szb.util.CheckInfoUtils;
import com.example.administrator.szb.util.DialogUtil;
import com.example.administrator.szb.util.FinishActivity;
import com.example.administrator.szb.util.NotificationMUtil;
import com.example.administrator.szb.util.Permission;
import com.example.administrator.szb.util.SPUtils;
import com.example.administrator.szb.util.StatusBarUtil;
import com.example.administrator.szb.util.Toasts;
import com.example.administrator.szb.util.UpdateAppService;
import com.example.administrator.szb.view.HomeIconPop;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class HomeActivity extends MVPBaseFragmentActivity {

    @Bind(R.id.content)
    FrameLayout content;
    @Bind(R.id.bll_1)
    LinearLayout bll1;
    @Bind(R.id.bll_2)
    LinearLayout bll2;
    @Bind(R.id.bll_3)
    LinearLayout bll3;
    @Bind(R.id.bll_4)
    LinearLayout bll4;
    @Bind(R.id.iv_home)
    ImageView ivHome;
    @Bind(R.id.tv_home)
    TextView tvHome;
    @Bind(R.id.iv_message)
    ImageView ivMessage;
    @Bind(R.id.tv_message)
    TextView tvMessage;
    @Bind(R.id.iv_zx)
    ImageView ivZx;
    @Bind(R.id.tv_zx)
    TextView tvZx;
    @Bind(R.id.iv_my)
    ImageView ivMy;
    @Bind(R.id.tv_my)
    TextView tvMy;
    @Bind(R.id.homepop)
    ImageView homepop;
    private  Boolean isQuit = false;
    private Timer timer = new Timer();
    FragmentHome fragmentHome;
    FragmentAsk fragmentAsk;
    FragmentTools fragmentZX;
    FragmentMy2 fragmentMy2;
    FragmentMy3 fragmentMy3;
    public static boolean IS_LOAD = false;
    private int selectTab = 0;
    private LinearLayout main_activity;
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    @Subscribe
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        main_activity = findViewById(R.id.main_activity);
        AndroidSetView.assistActivity(this,main_activity);
        //DialogUtil.showToast(activity,"有bug了，赶紧修复");

        //DialogUtil.showToast(activity,"bug已修复");
        FinishActivity.add(this);//将activity加入集合方便以后统一管理
        IS_LOAD  = true;

        //这个是设置状态栏为透明，注意不要在HomeActivity的布局中使用android:fitsSystemWindows="true"属性。会使得fragment中状态透明但是没有延伸从而多出空白


    }

    @Override
    protected void setBarColor() {
        StatusBarUtil.transparentStatusBar(this);
        //super.setBarColor();
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }
    @Override
    protected void initView() {
        ButterKnife.bind(this);
        chooseTab(0);
    }

    public static List<SuPeiBuiness>  suPeiBuiness;
    private boolean isQuit2 = false;
    @Override
    protected void initEvent() {
        homepop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               /* TipsPop.show(HomeActivity.this,homepop);
                if (true){
                    return;
                }
*/
                if (isQuit2 == false) {
                    isQuit2 = true;
                    //Toasts.show(getBaseContext(), "再按一次返回键退出程序", Toast.LENGTH_SHORT);
                    TimerTask task = null;
                    task = new TimerTask() {
                        @Override
                        public void run() {
                            isQuit2 = false;
                        }
                    };
                    timer.schedule(task, 1000);
                    if (suPeiBuiness!=null){
                        showHomeIconPop(null);
                        return;
                    }

                    homepop.setEnabled(false);

                    String url = URLAddress.SUPEI_BUINESS;
                    DialogUtil.showIsoProgressbar(context,"加载数据中");
                    Map<String,Object> map = new HashMap<String, Object>();
                    HttpUtils.post(activity,url, map, new OnResultListener() {
                        @Override
                        public void onSuccess(int requestCode, String str) {
                            DialogUtil.dialog_ios.dismiss();
                            SPUtils.setDatas("supeibuiness",str);
                            homepop.setEnabled(true);
                            showHomeIconPop(str);
                        }

                        @Override
                        public void onFailure(int requestCode, String str) {
                            DialogUtil.dialog_ios.dismiss();
                            homepop.setEnabled(true);
                            String string = SPUtils.getDatasString("supeibuiness");
                            if (string!=null){
                                showHomeIconPop(string);
                            }else {
                                DialogUtil.showToast(context, "请求失败");
                            }
                        }
                    });
                }


            }
        });
    }
    private void showHomeIconPop(String str){
        if (str!=null)
        suPeiBuiness = JSON.parseArray(str,SuPeiBuiness.class);
        HomeIconPop.show(HomeActivity.this,suPeiBuiness, main_activity, new HomeIconPop.OnItemClickLintener() {
            @Override
            public void onItemClick(final String name,final int id,final int pos) {
                CheckInfoUtils.check(activity, iosDiaolog, homepop, new CheckInfoUtils.OnSuccessLietener() {
                    @Override
                    public void onSuccess() {
                        if (suPeiBuiness.get(pos).getMold()==4){
                            Intent intent = new Intent(context, LuYanNewActivity.class);
                            startActivity(intent);
                        }else {
                            requestData(id,name,pos);
                        }
                    }
                });

            }
        });
    }
    @Override
    protected void initData() {
        Permission.isHaveRootActivity(this,Permission.SD_ARR,Permission.SD_CODE,this);

    }
    UpdateAppService updateAppService;
    @Override
    protected void onRequestPermissionsSuccess(int requestCode) {
        switch (requestCode){
            case Permission.SD_CODE:
                //TinkerInstaller.onReceiveUpgradePatch(getApplicationContext(),
               //         Environment.getExternalStorageDirectory().getAbsolutePath() + "/myTinkerDemo/test.apk");
                /*if (!DownLoadTinker.isStart){
                    Intent intent = new Intent(this,DownLoadTinker.class);
                    startService(intent);
                }*/
                tvMy.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                         updateAppService = new UpdateAppService(HomeActivity.this,tvMy);
                        updateAppService.checkVersion();
                    }
                },2000);

                break;
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN,priority = 100) //在ui线程执行 优先级100
    public void onDataSynEvent(DownIngBean event) {
       if (updateAppService!=null){
           updateAppService.showPoping(event);
       }
    }
    /**
     * 显示Fragment
     * @param i
     */
    public void initFragment(int i) {

        FragmentTransaction transaction = getFragmentTransaction();

        hideFragment(transaction);

        switch (i) {
            case 0:
                //首页
                if (fragmentHome!=null){
                    transaction.show(fragmentHome);
                }else {
                    fragmentHome = new FragmentHome();
                    transaction.add(R.id.content,fragmentHome);
                }

                break;
            case 1:
                //问答
                if (fragmentAsk!=null){
                    transaction.show(fragmentAsk);
                }else {
                    fragmentAsk = new FragmentAsk();
                    transaction.add(R.id.content,fragmentAsk);

                }
                break;
            case 2:
                //资讯
                if (fragmentZX!=null){
                    if (selecttool!=-1){
                        fragmentZX.setSelectTab(selecttool);
                    }

                    transaction.show(fragmentZX);
                }else {
                    fragmentZX = new FragmentTools();
                    if (selecttool!=-1){
                        fragmentZX.setSelectTab(selecttool);
                    }
                    transaction.add(R.id.content,fragmentZX);

                }
                selecttool = -1;
                break;
            case 3:
                //我的
                if (SPUtils.isLogin()){
                    //已登录
                    UserBase userInfo = SPUtils.getUserinfo();
                    //判断角色用户角色：1用户 2顾问
                    if (userInfo.getType()==2){
                        //顾问
                        if (fragmentMy3!=null){
                            transaction.show(fragmentMy3);
                        }else {
                            fragmentMy3 = new FragmentMy3();
                            transaction.add(R.id.content,fragmentMy3);

                        }

                    }else {
                        //普通用户
                        if (fragmentMy2!=null){
                            transaction.show(fragmentMy2);
                        }else {
                            fragmentMy2 = new FragmentMy2();
                            transaction.add(R.id.content,fragmentMy2);

                        }

                    }

                }else {
                    //未登录
                    startActivity(new Intent(context,LoginNewActivity_two.class));
                    return;
                }

                break;
        }
        changeStatu(i);
        selectTab=i;
        transaction.commitAllowingStateLoss();
    }
    private void hideFragment(FragmentTransaction transaction){
        if (fragmentHome!=null){
            transaction.hide(fragmentHome);
        }
        if (fragmentAsk!=null){
            transaction.hide(fragmentAsk);
        }
        if (fragmentZX!=null){
            transaction.hide(fragmentZX);
        }
        if (fragmentMy2!=null){
            transaction.hide(fragmentMy2);
        }
        if (fragmentMy3!=null){
            transaction.hide(fragmentMy3);
        }
    }

    @OnClick({R.id.bll_1, R.id.bll_2, R.id.bll_3, R.id.bll_4})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bll_1:
                chooseTab(0);
                break;
            case R.id.bll_2:
                chooseTab(1);
                break;
            case R.id.bll_3:
                chooseTab(2);
                break;
            case R.id.bll_4:
                chooseTab(3);
                break;
        }
    }
    public void chooseTab(int i) {
        resetStatu();//重置状态
        initFragment(i);
    }


    private void changeStatu(int i) {
        switch (i){
            case 0:
                ivHome.setImageResource(R.mipmap.home_choose);
                tvHome.setTextColor(getResources().getColor(R.color.tab_choose));

                ivMessage.setImageResource(R.mipmap.message);
                tvMessage.setTextColor(getResources().getColor(R.color.tab_unchoose));

                ivZx.setImageResource(R.mipmap.tools);
                tvZx.setTextColor(getResources().getColor(R.color.tab_unchoose));

                ivMy.setImageResource(R.mipmap.my);
                tvMy.setTextColor(getResources().getColor(R.color.tab_unchoose));
                break;
            case 1:
                ivHome.setImageResource(R.mipmap.home);
                tvHome.setTextColor(getResources().getColor(R.color.tab_unchoose));

                ivMessage.setImageResource(R.mipmap.message_choose);
                tvMessage.setTextColor(getResources().getColor(R.color.tab_choose));

                ivZx.setImageResource(R.mipmap.tools);
                tvZx.setTextColor(getResources().getColor(R.color.tab_unchoose));

                ivMy.setImageResource(R.mipmap.my);
                tvMy.setTextColor(getResources().getColor(R.color.tab_unchoose));
                break;
            case 2:
                ivHome.setImageResource(R.mipmap.home);
                tvHome.setTextColor(getResources().getColor(R.color.tab_unchoose));

                ivMessage.setImageResource(R.mipmap.message);
                tvMessage.setTextColor(getResources().getColor(R.color.tab_unchoose));

                ivZx.setImageResource(R.mipmap.tools_choose);
                tvZx.setTextColor(getResources().getColor(R.color.tab_choose));

                ivMy.setImageResource(R.mipmap.my);
                tvMy.setTextColor(getResources().getColor(R.color.tab_unchoose));
                break;
            case 3:
                ivHome.setImageResource(R.mipmap.home);
                tvHome.setTextColor(getResources().getColor(R.color.tab_unchoose));

                ivMessage.setImageResource(R.mipmap.message);
                tvMessage.setTextColor(getResources().getColor(R.color.tab_unchoose));

                ivZx.setImageResource(R.mipmap.tools);
                tvZx.setTextColor(getResources().getColor(R.color.tab_unchoose));

                ivMy.setImageResource(R.mipmap.my_choose);
                tvMy.setTextColor(getResources().getColor(R.color.tab_choose));
                break;
            default:
                break;
        }
    }



    private void resetStatu() {
        ivHome.setImageResource(R.mipmap.home);
        tvHome.setTextColor(getResources().getColor(R.color.tab_unchoose));

        ivMessage.setImageResource(R.mipmap.message);
        tvMessage.setTextColor(getResources().getColor(R.color.tab_unchoose));

        ivZx.setImageResource(R.mipmap.tools);
        tvZx.setTextColor(getResources().getColor(R.color.tab_unchoose));

        ivMy.setImageResource(R.mipmap.my);
        tvMy.setTextColor(getResources().getColor(R.color.tab_unchoose));
    }


    @Override
    public void onBackPressed() {
        HttpUtils.cancleTag(this);
        homepop.setEnabled(true);
        if (isQuit == false) {
            isQuit = true;
            Toasts.show(getBaseContext(), "再按一次返回键退出程序", Toast.LENGTH_SHORT);
            TimerTask task = null;
            task = new TimerTask() {
                @Override
                public void run() {
                    isQuit = false;
                }
            };
            timer.schedule(task, 2000);
        } else {
            finish();
            FinishActivity.finish();
            //android.os.Process.killProcess(android.os.Process.myPid());
            //System.exit(1);
        }
    }


    @Override
    protected void onRestart() {
        super.onRestart();
        chooseTab(selectTab);
    }

    @Subscribe(threadMode = ThreadMode.MAIN,priority = 100) //在ui线程执行 优先级100
    public void onDataSynEvent(JpushBean event) {
        if (fragmentHome!=null){
            fragmentHome.showMsg();
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        IS_LOAD = false;
        EventBus.getDefault().unregister(this);
    }

    //首页资讯，调研点击跳转到工具对应的页面
    private int selecttool = -1;

    public void setSelecttool(int selecttool) {
        this.selecttool = selecttool;
        chooseTab(2);
        canChangeTab = false;
    }
    public static boolean canChangeTab = false;
    public static int canChangeTabIndex = 0;
    @Override
    protected void onResume() {
        super.onResume();
        if (canChangeTab){
            setSelecttool(canChangeTabIndex);
        }

        if (TextUtils.isEmpty(SPUtils.getDatasString("notifyChecked"))){
            NotificationMUtil.isOpened(context);
        }

    }

    public int getSelecttool() {
        return selecttool;
    }


    /**
     * 中间大按钮点击item后的请求,然后跳转到速配发布页面
     */
    private void requestData(int id, final String name, final int pos) {
        if (suPeiBuiness.get(pos).getMold()==2){
            Intent intent = new Intent(context, SuPeiNew2Activity.class);
            intent.putExtra("speed_id",id);
            startActivity(intent);
        }else {
            Intent intent = new Intent(context, SuPeiNewActivity.class);
            intent.putExtra("mold",suPeiBuiness.get(pos).getMold());
            intent.putExtra("speed_id",suPeiBuiness.get(pos).getId());
            startActivity(intent);
        }

    }

}
